require('dotenv').config();
const mysql = require('mysql2/promise');
const fs = require('fs').promises;
const path = require('path');

async function initDatabase() {
    try {
        // 创建数据库连接
        const connection = await mysql.createConnection({
            host: process.env.DB_HOST || 'localhost',
            user: process.env.DB_USER || 'root',
            password: process.env.DB_PASSWORD || '',
            multipleStatements: true // 允许执行多条SQL语句
        });

        console.log('数据库连接成功');

        // 读取SQL文件
        const sqlFile = path.join(__dirname, '../sql/init.sql');
        const sql = await fs.readFile(sqlFile, 'utf8');

        // 执行SQL语句
        await connection.query(sql);
        console.log('数据库初始化成功');

        // 关闭连接
        await connection.end();
        console.log('数据库连接已关闭');
    } catch (error) {
        console.error('数据库初始化失败:', error);
        process.exit(1);
    }
}

// 执行初始化
initDatabase(); 